<script setup lang="tsx">
import type { MaybeRef, Position } from '@vueuse/core'

import { useAbsoluteDraggable } from 'fetm-hooks'
/**
 * 可拖拽拉伸的卡片
 */
import { ref } from 'vue'

defineOptions({
  name: 'DragResizeCard',
})

const props = withDefaults(defineProps<{
  containerElement: MaybeRef<HTMLElement | string | null | undefined>
  exceedable?: boolean
  title?: string
  unableDrag?: boolean
  dragInitialValue?: { x: number, y: number, [x: string]: any } | Position
  dragPositionType?: 'absolute' | 'fixed'
  bodyStyle?: Record<string, any>
}>(), {
  dragInitialValue: () => {
    return { x: 0, y: 0 }
  },
  dragPositionType: 'absolute',
  bodyStyle: () => new Object(),
})

const CardRef = ref<HTMLElement | null>(null)
const CardHeaderRef = ref<HTMLElement | null>(null)

// 一般的拖拽都是针对position为fixed，这里是absolute，需要特殊处理
const { styleComputed, style } = useAbsoluteDraggable(
  CardHeaderRef,
  CardRef,
  props.containerElement,
  {
    exceedable: props.exceedable,
    initialValue: props.dragInitialValue,
    onStart: () => {
      if (props.unableDrag) {
        return false
      }
    },
  },
)
</script>

<template>
  <div
    ref="CardRef"
    class="fetm-drag-resize-card"
    :class="[dragPositionType]"
    :style="dragPositionType == 'absolute' ? styleComputed : style"
  >
    <div
      ref="CardHeaderRef"
      class="fetm-drag-resize-card__header"
      :class="[!unableDrag ? 'cursor-move' : '']"
    >
      {{ title }}
      <slot name="header" />
    </div>
    <div class="fetm-drag-resize-card__body" :style="bodyStyle">
      <slot />
    </div>
  </div>
</template>

<style lang="less" scoped>
.fetm-drag-resize-card {
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  background-color: #fff;
  color: #000;
}

.fetm-drag-resize-card.fixed {
  position: fixed;
}

.fetm-drag-resize-card.absolute {
  position: absolute;
}

.fetm-drag-resize-card:hover,
.el-card:focus {
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
}

.fetm-drag-resize-card__header {
  padding: 10px 20px;
  border-bottom: 1px solid #e4e7ed;
  box-sizing: border-box;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: move;
  font-size: 16px;
  font-weight: bold;
}

.fetm-drag-resize-card__body {
  padding: 20px;
  overflow: hidden;
  resize: both;
  max-width: 100vw;
  max-height: 100vh;
  min-width: 30px;
  min-height: 30px;
}

.fetm-drag-resize-card.show-header {
  .fetm-drag-resize-card__body {
    height: calc(100% - 50px);
  }
}
</style>
